﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using StarsAdmin.Core.Helpers;
using System.Text;

namespace StarsAdmin.Core.App.Models
{
    public class Jwt
    {
        private readonly IConfiguration _configuration;
        private SymmetricSecurityKey _securityKey;
        private string _issuer;
        private string _audience;
        private int _expire;
        private int _refreshExpire;

        public Jwt(IConfiguration configuration)
        {
            _configuration = configuration.NotNull();
            Initialize();
        }

        /// <summary>
        /// 密钥
        /// </summary>
        public SymmetricSecurityKey SecurityKey { get => _securityKey; }

        /// <summary>
        /// 颁发者
        /// </summary>
        public string Issuer { get => _issuer; }

        /// <summary>
        /// 接收者
        /// </summary>
        public string Audience { get => _audience; }

        /// <summary>
        /// 有效期(分钟) 120 = 2小时
        /// </summary>
        public int Expire { get => _expire; }

        /// <summary>
        /// 刷新有效期(分钟) 1440 = 1天
        /// </summary>
        public int RefreshExpire { get => _refreshExpire; }

        /// <summary>
        /// 初始化Jwt配置
        /// </summary>
        /// <param name="configuration"></param>
        private void Initialize()
        {
            var jwtConfiguration = _configuration.GetSection("JwtConfiguration").NotNull();
            _issuer = jwtConfiguration.GetSection("Issuer").Value.NotNull();
            _audience = jwtConfiguration.GetSection("Audience").Value.NotNull();
            _securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfiguration.GetSection("SecurityKey").Value.NotNull()));
            _expire = int.Parse(jwtConfiguration.GetSection("Expire").Value.NotNull());
            _refreshExpire = int.Parse(jwtConfiguration.GetSection("RefreshExpire").Value.NotNull());
        }
    }
}